package linc.fun.openai.config.rabbit;

import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cloud.stream.binder.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import java.lang.reflect.Field;

/**
 * @author yqlin
 * @date 2023/5/10 12:50
 * @description
 */
@Configuration
public class RabbitConfig {
    @Resource
    private BinderFactory binderFactory;

    private final static String binderName = "default-binder";

    @Bean
    public RabbitTemplate rabbitTemplate() throws NoSuchFieldException, IllegalAccessException {
        // 获取目标binder
        Binder<BinderConfiguration, ? extends ConsumerProperties, ? extends ProducerProperties> binder =
                binderFactory.getBinder(binderName, BinderConfiguration.class);
        Assert.notNull(binder, binderName + " is null");
        // 获取binder的connectionFactory
        Field field = binder.getClass().getDeclaredField("connectionFactory");
        field.setAccessible(true);
        ConnectionFactory connectionFactory = (ConnectionFactory) field.get(binder);
        // new
        return new RabbitTemplate(connectionFactory);
    }

}
